<template>
  <div id="main" ref="chart" style="width: 600px; height: 400px;"></div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 使用 ECharts 的必要组件
echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer]);

export default {
  name: 'VehicleChart',
  methods: {
    async fetchVehicleData() {
      try {
        // 从后端API获取数据
        const response = await axios.get('http://localhost:8080/vehicles');
        return response.data;
      } catch (error) {
        console.error(error);
        return [];
      }
    },
    async renderChart() {
      const data = await this.fetchVehicleData();

      let pieData = data.map(vehicle => ({ value: vehicle.vehicleId, name: vehicle.ownerName }));

      // 初始化图表实例
      let myChart = echarts.init(this.$refs.chart);

      let option = {
        title: {
          text: 'Vehicle Owners',
          subtext: 'Pie Chart of Vehicle Owners',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Vehicle Owners',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      myChart.setOption(option);
    }
  },
  mounted() {
    this.renderChart();
  }
};
</script>

<style scoped>
#main {
  width: 100%;
  height: 100%;
}
</style>
